package com.yu.waterstation.system.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.yu.waterstation.common.common.exception.ServiceException;
import com.yu.waterstation.common.entity.app.Address;
import com.yu.waterstation.common.entity.app.Task;
import com.yu.waterstation.common.entity.app.dto.AddressDTO;
import com.yu.waterstation.common.entity.system.vo.AddressVO;
import com.yu.waterstation.system.common.util.session.SessionUtil;
import com.yu.waterstation.system.modules.app.mapper.AddressMapper;
import com.yu.waterstation.system.modules.app.mapper.TaskMapper;
import com.yu.waterstation.system.modules.app.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private TaskMapper taskMapper;

    // TODO 如何继承映射？？？ 这里为了一个taskStatus有点浪费了
    @Override
    public Page<AddressVO> getAddressesByConditions(String dorm, String room, int pageNo, int pageSize) {
        QueryWrapper<Address> wrapper = new QueryWrapper<Address>();
        if (!StringUtils.isEmpty(dorm)) {
            wrapper.eq("dorm", dorm);
            if (!StringUtils.isEmpty(room))
                wrapper.eq("room", room);
        }
        wrapper.orderByAsc("dorm", "room");
        Page<Address> page = addressMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
        List<AddressVO> list = new ArrayList<>();
        // 查询订水状态
        for (Address address : page.getRecords()) {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(address, addressVO);
            addressVO.setTaskStatus(taskMapper.selectCountById(address.getId()) >= 1);
            list.add(addressVO);
        }
        return new Page<AddressVO>(pageNo, pageSize, page.getTotal()).setRecords(list);
    }

    @Override
    public List<?> getDormList() {
        return addressMapper.selectObjs(new QueryWrapper<Address>()
                .select("dorm")
                .groupBy("dorm").orderByAsc("dorm"));
    }

    @Override
    public List<?> getRoomsOfDorm(String dorm) throws ServiceException {
        if (StringUtils.isEmpty(dorm))
            return new ArrayList<>(0);
        return addressMapper.selectObjs(new QueryWrapper<Address>()
                .select("room")
                .eq("dorm", dorm).orderByAsc("room"));

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addAddress(Address address) {
        return addressMapper.insert(address);
    }

    @Transactional
    @Override
    public int deleteAddressBatchIds(List<Integer> addressIdList) {
        return addressMapper.deleteBatchIds(addressIdList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateAddress(Address address) {
        return addressMapper.updateById(address);
    }

    // 切换叫水状态（叫水或取消叫水）
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changeTaskStatus(Integer addressId, HttpServletRequest request) throws ServiceException {
        Address address = addressMapper.selectById(addressId);

        Task task = taskMapper.selectById(addressId);
        if (task == null) {
            if (address.getTicketNum() <= 0)
                throw ServiceException.CONST_ticket_num_is_not_enough;
            task = new Task();
            task.setAddressId(addressId);
            task.setPublisher("管理员-" + SessionUtil.getCurrentSysUserUsername(request));
            task.setTimestamp(new Date());
            taskMapper.insert(task);
        } else { // 取消叫水
            taskMapper.deleteById(addressId);
        }
    }
}
